'use strict'

import { app, BrowserWindow, Menu, ipcMain, globalShortcut } from 'electron'

import * as express from 'express'
import * as expressWebSocket from 'express-ws'
import webSocketStream from 'websocket-stream/stream'
import ffmpeg from 'fluent-ffmpeg'

/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */

if (process.env.NODE_ENV !== 'development') {
  global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}
app.allowRendererProcessReuse = true

function localServer() {
  let app = express()
  app.use(express.static(__dirname))
  expressWebSocket(app, null, {
    perMessageDeflate: true
  })
  app.ws('/rtsp/:id/', rtspRequestHandle)
  app.listen(8888)
}

function rtspRequestHandle(ws, req) {
  const stream = webSocketStream(
    ws,
    {
      binary: true,
      browserBufferTimeout: 1000000
    },
    {
      browserBufferTimeout: 1000000
    }
  )
  let url = req.query.url
  // try {
  ffmpeg(url)
    .addInputOption('-rtsp_transport', 'tcp', '-buffer_size', '102400') // 这里可以添加一些 RTSP 优化的参数
    .on('start', function () {})
    .on('codecData', function () {
      // 摄像机在线处理
    })
    .on('error', function () {})
    .on('end', function () {
      // 摄像机断线的处理
    })
    .outputFormat('flv')
    .videoCodec('copy')
    .noAudio()
    .pipe(stream)
  // } catch (error) {
  //   console.log(error)
  // }
}

// 关闭顶部菜单栏
Menu.setApplicationMenu(null)

let mainWindow
const winURL = process.env.NODE_ENV === 'development' ? `http://localhost:9080` : `file://${__dirname}/index.html`

function createWindow() {
  /**
   * Initial window options
   */
  mainWindow = new BrowserWindow({
    frame: false, // 关闭顶部标题栏
    height: 711, // 缩小时默认高度
    useContentSize: true,
    width: 1266, // 缩小时默认宽度
    minWidth: 1266,
    minHeight: 711,
    webPreferences: {
      webSecurity: false,
      nodeIntegration: true
    }
  })
  mainWindow.maximize()
  mainWindow.loadURL(winURL)
  globalShortcut.register('ctrl+f12', function () {
    mainWindow.webContents.toggleDevTools()
  })
  mainWindow.on('closed', () => {
    mainWindow = null
  })
}

ipcMain.on('min', e => mainWindow.minimize())
ipcMain.on('max', e => {
  if (mainWindow.isMaximized()) {
    mainWindow.unmaximize()
  } else {
    mainWindow.maximize()
  }
})
// 执行关闭 自定义关闭
ipcMain.on('handelClose', function (res) {
  app.quit()
})

const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
  app.quit()
} else {
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    // 当运行第二个实例时,将会聚焦到mainWindow这个窗口
    if (mainWindow) {
      if (mainWindow.isMinimized()) mainWindow.restore()
      mainWindow.focus()
      mainWindow.show()
    }
  })
  app.on('ready', localServer)

  app.on('ready', createWindow)

  app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
      app.quit()
    }
  })

  app.on('activate', () => {
    if (mainWindow === null) {
      createWindow()
    }
  })
}

/**
 * Auto Updater
 *
 * Uncomment the following code below and install `electron-updater` to
 * support auto updating. Code Signing with a valid certificate is required.
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
 */

/*
import { autoUpdater } from 'electron-updater'

autoUpdater.on('update-downloaded', () => {
  autoUpdater.quitAndInstall()
})

app.on('ready', () => {
  if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
})
 */
